using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine.Profiling;
using UnityEditor;

public class PerformanceManager : MonoBehaviour
{
    [Header("性能监控设置")]
    public bool enablePerformanceMonitoring = true;
    public bool showPerformanceUI = false;
    public float updateInterval = 1f;
    public bool logPerformanceData = false;
    
    [Header("性能阈值")]
    public float targetFPS = 60f;
    public float lowFPSThreshold = 30f;
    public long maxMemoryUsage = 512 * 1024 * 1024; // 512MB
    public int maxGameObjects = 1000;
    public float maxFrameTime = 16.67f; // 60FPS对应的帧时间
    
    [Header("优化设置")]
    public bool autoOptimization = true;
    public bool enableObjectPooling = true;
    public bool enableLODSystem = true;
    public bool enableCulling = true;
    public bool enableBatching = true;
    
    [Header("调试设置")]
    public bool showDebugInfo = true;
    public KeyCode toggleUIKey = KeyCode.F1;
    
    // 单例模式
    public static PerformanceManager Instance { get; private set; }
    
    // 性能数据
    private PerformanceData currentPerformance;
    private Queue<float> fpsHistory;
    private Queue<long> memoryHistory;
    private int historySize = 60; // 保存60秒的历史数据
    
    // 优化状态
    private Dictionary<string, bool> optimizationStates;
    private float lastOptimizationTime = 0f;
    private float optimizationCooldown = 5f;
    
    // UI相关
    private GUIStyle labelStyle;
    private bool uiInitialized = false;
    
    // 事件
    public event Action<PerformanceData> OnPerformanceUpdated;
    public event Action<PerformanceIssue> OnPerformanceIssue;
    public event Action<string> OnOptimizationApplied;
    
    [System.Serializable]
    public class PerformanceData
    {
        public float fps;
        public float frameTime;
        public long memoryUsage;
        public int gameObjectCount;
        public int activeEnemies;
        public int activeBullets;
        public int activeParticles;
        public float cpuUsage;
        public float gpuUsage;
        public int drawCalls;
        public int triangles;
        public float timestamp;
    }
    
    [System.Serializable]
    public class PerformanceIssue
    {
        public PerformanceIssueType type;
        public float severity; // 0-1
        public string description;
        public string suggestion;
        public float timestamp;
    }
    
    public enum PerformanceIssueType
    {
        LowFPS,
        HighMemoryUsage,
        TooManyGameObjects,
        HighFrameTime,
        TooManyDrawCalls,
        MemoryLeak
    }
    
    void Awake()
    {
        // 单例模式实现
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
            InitializePerformanceManager();
        }
        else
        {
            Destroy(gameObject);
        }
    }
    
    void InitializePerformanceManager()
    {
        currentPerformance = new PerformanceData();
        fpsHistory = new Queue<float>();
        memoryHistory = new Queue<long>();
        
        optimizationStates = new Dictionary<string, bool>
        {
            { "ObjectPooling", enableObjectPooling },
            { "LODSystem", enableLODSystem },
            { "Culling", enableCulling },
            { "Batching", enableBatching }
        };
        
        // 设置Unity性能相关设置
        Application.targetFrameRate = (int)targetFPS;
        QualitySettings.vSyncCount = 0; // 禁用垂直同步以获得更准确的FPS测量
        
        // 开始性能监控
        if (enablePerformanceMonitoring)
        {
            StartCoroutine(PerformanceMonitoringCoroutine());
        }
        
        Debug.Log($"性能管理器已初始化 - 目标FPS: {targetFPS}");
    }
    
    IEnumerator PerformanceMonitoringCoroutine()
    {
        while (enablePerformanceMonitoring)
        {
            UpdatePerformanceData();
            CheckPerformanceIssues();
            
            if (autoOptimization)
            {
                ApplyAutoOptimizations();
            }
            
            yield return new WaitForSeconds(updateInterval);
        }
    }
    
    void UpdatePerformanceData()
    {
        // 更新FPS
        currentPerformance.fps = 1f / Time.unscaledDeltaTime;
        currentPerformance.frameTime = Time.unscaledDeltaTime * 1000f; // 转换为毫秒
        
        // 更新内存使用
        currentPerformance.memoryUsage = Profiler.GetTotalAllocatedMemoryLong();
        
        // 更新游戏对象数量
        currentPerformance.gameObjectCount = FindObjectsOfType<GameObject>().Length;
        
        // 更新游戏特定对象数量
        currentPerformance.activeEnemies = FindObjectsOfType<EnemyController>().Length;
        currentPerformance.activeBullets = FindObjectsOfType<BulletController>().Length;
        currentPerformance.activeParticles = FindObjectsOfType<ParticleSystem>().Length;
        
        // 更新渲染统计
        currentPerformance.drawCalls = UnityStats.drawCalls; // 获取当前场景的绘制调用次数
        currentPerformance.triangles = 0; // 占位符
        
        currentPerformance.timestamp = Time.time;
        
        // 更新历史数据
        UpdateHistoryData();
        
        // 触发事件
        OnPerformanceUpdated?.Invoke(currentPerformance);
        
        if (logPerformanceData)
        {
            LogPerformanceData();
        }
    }
    
    void UpdateHistoryData()
    {
        fpsHistory.Enqueue(currentPerformance.fps);
        memoryHistory.Enqueue(currentPerformance.memoryUsage);
        
        // 保持历史数据大小
        while (fpsHistory.Count > historySize)
        {
            fpsHistory.Dequeue();
        }
        
        while (memoryHistory.Count > historySize)
        {
            memoryHistory.Dequeue();
        }
    }
    
    void CheckPerformanceIssues()
    {
        // 检查低FPS
        if (currentPerformance.fps < lowFPSThreshold)
        {
            ReportPerformanceIssue(new PerformanceIssue
            {
                type = PerformanceIssueType.LowFPS,
                severity = 1f - (currentPerformance.fps / targetFPS),
                description = $"FPS过低: {currentPerformance.fps:F1}",
                suggestion = "考虑减少屏幕上的对象数量或降低画质设置",
                timestamp = Time.time
            });
        }
        
        // 检查内存使用
        if (currentPerformance.memoryUsage > maxMemoryUsage)
        {
            ReportPerformanceIssue(new PerformanceIssue
            {
                type = PerformanceIssueType.HighMemoryUsage,
                severity = (float)currentPerformance.memoryUsage / maxMemoryUsage - 1f,
                description = $"内存使用过高: {currentPerformance.memoryUsage / (1024 * 1024):F1}MB",
                suggestion = "启用对象池或清理未使用的资源",
                timestamp = Time.time
            });
        }
        
        // 检查游戏对象数量
        if (currentPerformance.gameObjectCount > maxGameObjects)
        {
            ReportPerformanceIssue(new PerformanceIssue
            {
                type = PerformanceIssueType.TooManyGameObjects,
                severity = (float)currentPerformance.gameObjectCount / maxGameObjects - 1f,
                description = $"游戏对象过多: {currentPerformance.gameObjectCount}",
                suggestion = "使用对象池管理子弹和敌人",
                timestamp = Time.time
            });
        }
        
        // 检查帧时间
        if (currentPerformance.frameTime > maxFrameTime)
        {
            ReportPerformanceIssue(new PerformanceIssue
            {
                type = PerformanceIssueType.HighFrameTime,
                severity = currentPerformance.frameTime / maxFrameTime - 1f,
                description = $"帧时间过长: {currentPerformance.frameTime:F2}ms",
                suggestion = "优化游戏逻辑或减少计算复杂度",
                timestamp = Time.time
            });
        }
    }
    
    void ReportPerformanceIssue(PerformanceIssue issue)
    {
        OnPerformanceIssue?.Invoke(issue);
        
        if (showDebugInfo)
        {
            Debug.LogWarning($"性能问题: {issue.description} - {issue.suggestion}");
        }
    }
    
    void ApplyAutoOptimizations()
    {
        if (Time.time - lastOptimizationTime < optimizationCooldown)
        {
            return;
        }
        
        bool optimizationApplied = false;
        
        // 根据性能问题自动应用优化
        if (currentPerformance.fps < lowFPSThreshold)
        {
            if (currentPerformance.activeBullets > 100 && !optimizationStates["ObjectPooling"])
            {
                EnableObjectPooling();
                optimizationApplied = true;
            }
            else if (currentPerformance.activeEnemies > 20 && !optimizationStates["Culling"])
            {
                EnableCulling();
                optimizationApplied = true;
            }
        }
        
        if (currentPerformance.memoryUsage > maxMemoryUsage * 0.8f)
        {
            ForceGarbageCollection();
            optimizationApplied = true;
        }
        
        if (optimizationApplied)
        {
            lastOptimizationTime = Time.time;
        }
    }
    
    void EnableObjectPooling()
    {
        optimizationStates["ObjectPooling"] = true;
        
        // 通知相关系统启用对象池
        BulletSpawner bulletSpawner = FindObjectOfType<BulletSpawner>();
        if (bulletSpawner != null)
        {
            bulletSpawner.EnableObjectPooling(true);
        }
        
        TreasureSpawner treasureSpawner = FindObjectOfType<TreasureSpawner>();
        if (treasureSpawner != null)
        {
            // treasureSpawner.EnableObjectPooling(true);
        }
        
        OnOptimizationApplied?.Invoke("启用对象池");
        
        if (showDebugInfo)
        {
            Debug.Log("性能优化: 启用对象池");
        }
    }
    
    void EnableCulling()
    {
        optimizationStates["Culling"] = true;
        
        // 启用视锥剔除
        Camera mainCamera = Camera.main;
        if (mainCamera != null)
        {
            mainCamera.cullingMask = -1; // 确保剔除启用
        }
        
        OnOptimizationApplied?.Invoke("启用视锥剔除");
        
        if (showDebugInfo)
        {
            Debug.Log("性能优化: 启用视锥剔除");
        }
    }
    
    void ForceGarbageCollection()
    {
        System.GC.Collect();
        Resources.UnloadUnusedAssets();
        
        OnOptimizationApplied?.Invoke("强制垃圾回收");
        
        if (showDebugInfo)
        {
            Debug.Log("性能优化: 强制垃圾回收");
        }
    }
    
    void LogPerformanceData()
    {
        Debug.Log($"性能数据 - FPS: {currentPerformance.fps:F1}, 内存: {currentPerformance.memoryUsage / (1024 * 1024):F1}MB, " +
                 $"对象: {currentPerformance.gameObjectCount}, 敌人: {currentPerformance.activeEnemies}, " +
                 $"子弹: {currentPerformance.activeBullets}");
    }
    
    // 公共方法：获取当前性能数据
    public PerformanceData GetCurrentPerformance()
    {
        return currentPerformance;
    }
    
    // 公共方法：获取平均FPS
    public float GetAverageFPS()
    {
        if (fpsHistory.Count == 0) return 0f;
        
        float sum = 0f;
        foreach (float fps in fpsHistory)
        {
            sum += fps;
        }
        
        return sum / fpsHistory.Count;
    }
    
    // 公共方法：获取内存使用趋势
    public bool IsMemoryIncreasing()
    {
        if (memoryHistory.Count < 10) return false;
        
        long[] memoryArray = memoryHistory.ToArray();
        int recentCount = 10;
        
        long recentAvg = 0;
        long olderAvg = 0;
        
        for (int i = memoryArray.Length - recentCount; i < memoryArray.Length; i++)
        {
            recentAvg += memoryArray[i];
        }
        recentAvg /= recentCount;
        
        for (int i = memoryArray.Length - recentCount * 2; i < memoryArray.Length - recentCount; i++)
        {
            olderAvg += memoryArray[i];
        }
        olderAvg /= recentCount;
        
        return recentAvg > olderAvg * 1.1f; // 增长超过10%
    }
    
    // 公共方法：手动触发优化
    public void TriggerOptimization(string optimizationType)
    {
        switch (optimizationType.ToLower())
        {
            case "objectpooling":
                EnableObjectPooling();
                break;
            case "culling":
                EnableCulling();
                break;
            case "gc":
                ForceGarbageCollection();
                break;
            default:
                if (showDebugInfo)
                {
                    Debug.LogWarning($"未知的优化类型: {optimizationType}");
                }
                break;
        }
    }
    
    // 公共方法：设置性能目标
    public void SetPerformanceTarget(float fps, long maxMemory)
    {
        targetFPS = fps;
        maxMemoryUsage = maxMemory;
        Application.targetFrameRate = (int)targetFPS;
        
        if (showDebugInfo)
        {
            Debug.Log($"性能目标已更新 - FPS: {targetFPS}, 内存: {maxMemoryUsage / (1024 * 1024)}MB");
        }
    }
    
    void Update()
    {
        // 切换性能UI显示
        if (Input.GetKeyDown(toggleUIKey))
        {
            showPerformanceUI = !showPerformanceUI;
        }
    }
    
    void OnGUI()
    {
        if (!showPerformanceUI) return;
        
        if (!uiInitialized)
        {
            InitializeUI();
        }
        
        DrawPerformanceUI();
    }
    
    void InitializeUI()
    {
        labelStyle = new GUIStyle(GUI.skin.label)
        {
            fontSize = 14,
            normal = { textColor = Color.white }
        };
        
        uiInitialized = true;
    }
    
    void DrawPerformanceUI()
    {
        float panelWidth = 300f;
        float panelHeight = 200f;
        Rect panelRect = new Rect(10, 10, panelWidth, panelHeight);
        
        GUI.Box(panelRect, "性能监控");
        
        float yOffset = 30f;
        float lineHeight = 20f;
        
        GUI.Label(new Rect(20, yOffset, panelWidth - 20, lineHeight), 
                 $"FPS: {currentPerformance.fps:F1} (目标: {targetFPS})", labelStyle);
        yOffset += lineHeight;
        
        GUI.Label(new Rect(20, yOffset, panelWidth - 20, lineHeight), 
                 $"帧时间: {currentPerformance.frameTime:F2}ms", labelStyle);
        yOffset += lineHeight;
        
        GUI.Label(new Rect(20, yOffset, panelWidth - 20, lineHeight), 
                 $"内存: {currentPerformance.memoryUsage / (1024 * 1024):F1}MB", labelStyle);
        yOffset += lineHeight;
        
        GUI.Label(new Rect(20, yOffset, panelWidth - 20, lineHeight), 
                 $"游戏对象: {currentPerformance.gameObjectCount}", labelStyle);
        yOffset += lineHeight;
        
        GUI.Label(new Rect(20, yOffset, panelWidth - 20, lineHeight), 
                 $"敌人: {currentPerformance.activeEnemies} | 子弹: {currentPerformance.activeBullets}", labelStyle);
        yOffset += lineHeight;
        
        GUI.Label(new Rect(20, yOffset, panelWidth - 20, lineHeight), 
                 $"平均FPS: {GetAverageFPS():F1}", labelStyle);
        yOffset += lineHeight;
        
        // 优化按钮
        if (GUI.Button(new Rect(20, yOffset, 80, 20), "强制GC"))
        {
            TriggerOptimization("gc");
        }
        
        if (GUI.Button(new Rect(110, yOffset, 80, 20), "对象池"))
        {
            TriggerOptimization("objectpooling");
        }
        
        if (GUI.Button(new Rect(200, yOffset, 80, 20), "剔除"))
        {
            TriggerOptimization("culling");
        }
    }
    
    void OnDrawGizmos()
    {
        if (!showDebugInfo) return;

        // 在编辑器下，OnDrawGizmos 可能在 Awake 之前调用，需判空
        if (currentPerformance == null)
        {
            Gizmos.color = Color.gray;
            Gizmos.DrawWireCube(transform.position, Vector3.one);
            return;
        }

        // 根据性能状态显示不同颜色
        if (currentPerformance.fps < lowFPSThreshold)
        {
            Gizmos.color = Color.red;
        }
        else if (currentPerformance.fps < targetFPS * 0.8f)
        {
            Gizmos.color = Color.yellow;
        }
        else
        {
            Gizmos.color = Color.green;
        }
        
        Gizmos.DrawWireCube(transform.position, Vector3.one);
    }
}